<?php
@header('Content-Type: text/html; charset=utf-8');
define("MAXRECORDS", 10);
define("MSGTYPE", "news");

SearchKeywordAndPrint($_GET[keyword]);

function SearchKeywordAndPrint($k){
	$con = mysql_connect("tanghn.xicp.net","root","redhat");
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}

	$text = $k;
	/*$text = iconv("UTF-8", "GBK//IGNORE", $text);
	$text = urlencode($text);
	$result = file_get_contents("http://192.168.1.22:1985/?w=".$text);
	$result = iconv("GBK", "UTF-8//IGNORE", $result);*/
	$result ="芝士 蛋 堡";
	echo "分词结果：".$result."<br /><br />";

	$fenci = explode(" ", $result);

	mysql_select_db("kfcmenu", $con);
	mysql_query("set names utf8");

	$temp = "SELECT * FROM kfcmenu";
	$db_result = mysql_query($temp);

	unset($lines_array);
	$lines_array = array();
	while($row = mysql_fetch_array($db_result))
	{
		$match_times = 0;
		/*unset($lines_array); 清空变量*/

		foreach ($fenci as $current_keyword){
				if(eregi($current_keyword, $row['keyword']))  /*strstr不能匹配，不明原因。使用正则表达式*/
				/*if(false != stristr($current_keyword, $row['keyword']))*/
				{
					$match_times++;
				}
		}
		if($match_times>0){
			$temp = array($row, $match_times);
			array_push($lines_array, $temp);
		}else{
			continue;
		}
	}

	usort($lines_array, 'compare');

	foreach ($lines_array as $the_hit_line){
			/*print_r($the_hit_line);*/
			$hit_row = $the_hit_line[0];
			echo "<p><strong>";
			echo htmlspecialchars(stripslashes($hit_row['name']));
			echo "</strong><br />Price: ";
			echo stripslashes($hit_row['price']);
			echo "<br />Description: ";
			echo stripslashes($hit_row['description']);
			echo "<br />Keyword: ";
			echo stripslashes($hit_row['keyword']);
			echo "<br />Match times: ";
			echo stripslashes($the_hit_line[1]);
			echo "</p>";
	}
	echo PrintMenuFormat($lines_array);
	mysql_close($con);
}
/*逆序*/
function compare($x, $y){
	if($x[1] == $y[1]){
		return 0;
	}else if($x[1] < $y[1]){
		return 1;
	}else{
		return -1;
	}
}


function PrintMenuFormat($lines_array){
	$counter = count($lines_array);
	$counter = ($counter>MAXRECORDS) ? MAXRECORDS : $counter;
	echo "number :".$counter;
	
	/*$textTpl = sprintf("<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[MSGTYPE]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							", $counter);*/
echo "***********************************";						
	for($i=0; $i < 1; $i++){

		$row = $lines_array[$i][0];
		echo $row['name'];
		echo $row['price'];
		
		
		$textTpl = "<Articles>
				<item>
				<Title><![CDATA[%s]]></Title> 
				<Description><![CDATA[%s]></Description>
				<PicUrl><![CDATA[%s]]></PicUrl>
				<Url><![CDATA[%s]]></Url>
				</item>
				</Articles>";
		$resultstr = sprintf($textTpl, $row['name'], $row['price'], "http://tanghn.xicp.net/01.png", "www.baidu.com");
		echo $resultstr;
	}
echo "***********************************";
}
?>